<template>

    <!-- 添加或修改对话框 -->
    <lam-dialog :title="title" :visible.sync="open" width="80%" top="3vh" @close="cancel">
      <el-form :ref="formRef" :model="form" :rules="rules" label-width="100px" :disabled="formDisabled">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="imgs">
              <MulPicUpload v-model="form.imgs" busiModule="product"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品主图" prop="pic">
              <PicUpload v-model="form.pic" busiModule="product"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <treeselect v-model="form.categoryId" :options="treeData" :show-count="true" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分组" prop="tagList">
              <lam-dict-select type="multipleSelect" v-model="form.tagList" :collapse-tags="false" dictCode="prodTag" dictType="tableDict"
                  :useSpliter="false" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="prodName">
              <el-input v-model="form.prodName" type="textarea" autosize placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="简要卖点" prop="brief">
              <el-input v-model="form.brief" autosize placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <lam-dict-select type="radio" v-model="form.status" dictCode="prod_status_sell" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="配送方式" prop="deliveryMode">
              <lam-dict-select type="checkbox" v-model="form.deliveryMode" dictCode="delivery_mode" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="shopDeliveryMode">
            <el-form-item label="运费模板" prop="deliveryTemplateId">
              <lam-dict-select v-model="form.deliveryTemplateId" dictCode="transDeeTemplate" dictType="tableDict" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="shopDeliveryMode && form.deliveryTemplateId">
            <el-form-item>
              <TransFeeTempDetail :transFeeTemplateId="form.deliveryTemplateId" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <!-- <sku-tag ref="skuTag" :skuList="form.skuList" @change="skuTagChangeSkuHandler"></sku-tag> -->
          <SkuProperties ref="skuProperties" :skuPropertiesList="form.skuPropertiesList" @change="skuPropertiesChange"/>

          <SkuTable ref="skuTable" v-model="form.skuList" :skuPropertiesList="form.skuPropertiesList" @change="skuListChange"/>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="详细描述" prop="content">
              <tiny-mce v-model="form.content" ref="content" style="width:100%" v-if="open"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </lam-dialog>

</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import PicUpload from '@/components/PicUpload';
import MulPicUpload from '@/components/PicUpload/MulPicUpload'
import TinyMce from '@/components/tiny-mce'
import { EditMixin } from '@/components/mixins/EditMixin';
import TransFeeTempDetail from '@/views/mall/transFeeTemplate/TransFeeTempDetail';
// import SkuTag from './sku-tag'
import SkuTable from './skuTable'
import SkuProperties from './skuProperties'

export default {
  name: "EditProduct",
  mixins:[EditMixin],
  components:{
    Treeselect,
    PicUpload,
    MulPicUpload,
    TransFeeTempDetail,
    // SkuTag,
    SkuTable,
    SkuProperties,
    TinyMce,
  },
  data() {
    return {
      url: {
        base: '/mall/product/',
        listCategoryTree: '/mall/category/treeselect'
      },
      // 表单校验
      rules: {
        prodName: [{required: true, message: "商品名称不能为空", trigger: "blur" }, {validator: this.prodNameUniqueValidator, trigger: 'blur'}],
        oriPrice: [{ required: true, message: "原价不能为空", trigger: "blur" }],
        price: [{ required: true, message: "现价不能为空", trigger: "blur" }],
        content: [{ required: true, message: "详细描述不能为空", trigger: "blur" }],
        imgs: [{ required: true, message: "请选择商品图片", trigger: "blur" }],
        pic: [{ required: true, message: "请选择商品主图", trigger: "blur" }],
        deliveryMode: [{ required: true, message: "请选择配送方式", trigger: "blur" }],
        categoryId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
        deliveryTemplateId: [{ required: true, message: "请选择运费模板", trigger: "blur" }],
        tagList: [{ required: true, message: "请选择商品分组", trigger: "blur" }],
      },
      treeData:[],
      inited: false
    };
  },
  computed:{
    shopDeliveryMode(){
      let arr = this.form.deliveryMode;
      return arr && arr.length && arr.indexOf('shopDelivery')>-1;
    },
  },
  watch:{
    'form.prodName' : function(newVal, oldVal){
      newVal = !!newVal?newVal:'';
      this.form.skuList.forEach(sku => {
        if(!sku.prodName){
          sku.prodName = newVal + ' ' + sku.skuName;
        }else if(!sku.prodName.startsWith(newVal)){
          sku.prodName = sku.prodName.replace(oldVal, newVal);
        }
      })
    }
  },
  created() {
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        prodName: null,
        brief: null,
        content: null,
        pic: null,
        imgs: null,
        status: 1,
        categoryId: null,
        tagList:[],
        deliveryMode: 'shopDelivery',
        deliveryTemplateId: null,
        skuList: [],
        skuPropertiesList:[]
      };
    },

    beforeOpen(title, operType, res){
      this.$httpGet(this.url.listCategoryTree).then(res => {
        this.treeData = res.data;
      });
    },

    skuPropertiesChange (skuPropertiesList, skuList) {
      this.form.skuPropertiesList = skuPropertiesList;
      this.form.skuList = skuList;
      this.form.skuList.forEach(sku => {
        if(!sku.prodName || !sku.prodName.startsWith(this.form.prodName)){
          sku.prodName = this.form.prodName + ' ' + sku.skuName;
        }
      })
    },
    skuListChange (skuList) {
      this.form.skuList = skuList;
      this.form.skuList.forEach(sku => {
        if(!sku.prodName || !sku.prodName.startsWith(this.form.prodName)){
          sku.prodName = this.form.prodName + ' ' + sku.skuName;
        }
      })
    },

    prodNameUniqueValidator(rule, value, callback) {
      let param = {prodName: value};
      if(this.operType=='update') param.id = this.form.id;
      this.checkUniqueAsyn(value, callback, 'productProdName', param);
    },

    calcPriceAndStocks (data) {
      data.totalStocks = 0; // 商品库存
      data.price = 0; // 商品价格
      data.oriPrice = 0; // 商品原价
      // 商品实际库存
      for (let i = 0; i < data.skuList.length; i++) {
        const skuItem = data.skuList[i]
        if (skuItem.status !== 1) {
          continue
        }
        if (data.price === 0) {
          data.price = skuItem.price ? Number.parseFloat(skuItem.price) : 0
        }
        // 商品价格为最低价的那件商品的价格
        data.price = Math.min(data.price, skuItem.price)
        if (data.price === skuItem.price) {
          data.oriPrice = skuItem.oriPrice ? Number.parseFloat(skuItem.oriPrice) : 0
        }
        data.totalStocks += skuItem.stocks ? Number.parseInt(skuItem.stocks) : 0
      }

    },

    /** 提交按钮 */
    submitForm(){
      this.loading = true;
      this.$refs[this.formRef].validate(valid => {
        if (!valid) {
          this.loading = false;
          return;
        }
        let data = Object.assign({}, this.form);
        // 设置价格和库存
        this.calcPriceAndStocks(data);
        let proms = this.operType=='update' ? this.$httpPut(this.url.base, data) : this.$httpPost(this.url.base, data);
        proms.then(res => {
          this.msgSuccess("操作成功");
          this.open = false;
          this.$emit('ok');
        }).catch(()=>{}).finally(()=>{
          this.loading = false;
        });
      });
    }

  }
};
</script>
